package com.cjm.algorithm.tree;

import com.cjm.algorithm.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class Ti129 {
    public static void main(String[] args) {
        System.err.println("0".substring(0,1));
    }

    private List<Integer> sums = new ArrayList<>();
    public int sumNumbers(TreeNode root) {
        sums.clear();
        // 前序遍历
        // 子节点时终止
        methodSumBers(root, new StringBuilder(""));
        return sums.stream().reduce(Integer::sum).orElse(0);
    }

    private void methodSumBers(TreeNode root, StringBuilder sb) {
        sb.append(root.val);
        if (root.left == null && root.right == null) {
            sums.add(Integer.valueOf(sb.toString()));
            sb.deleteCharAt(sb.length() - 1);
            return ;
        }
        if (root.left != null) {
            methodSumBers(root.left, sb);
        }
        if (root.right != null) {
            methodSumBers(root.right, sb);
        }
        sb.deleteCharAt(sb.length() - 1);
    }
}
